package com.md.entity;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.persistence.Entity;

import com.md.exception.SystemException;


public abstract class EntityRecord implements BaseEntity, Cloneable {

	private Object identifier = null;

	private transient Map<String, Object> extendedValues = null;

	public Object getIdentifier() {
		return this.identifier;
	}

	public void setIdentifier(Object identifier) {
		this.identifier = identifier;
	}

	public Map<String, Object> getExtendedValues() {
		return this.extendedValues;
	}

	public Object getExtendedValue(String name) {
		if (this.extendedValues == null) {
			return null;
		}
		return extendedValues.get(name);
	}

	public void setExtendedValue(String name, Object value) {
		if (this.extendedValues == null) {
			this.extendedValues = new ConcurrentHashMap<String, Object>();
		}
		if (value == null) {
			this.extendedValues.remove(name);
		} else {
			this.extendedValues.put(name, value);
		}
	}

	public String symbol() {
		return this.getClass().getAnnotation(Entity.class).name();
	}

	@Override
	public boolean equals(Object obj) {
		if (!(obj instanceof EntityRecord)) {
			return false;
		} else if (this.getIdentifier() == null) {
			return super.equals(obj);
		} else {
			return this.getIdentifier().equals(((EntityRecord) obj).getIdentifier());
		}
	}

	@Override
	public BaseEntity clone() {
		try {
			EntityRecord baseEntity = (EntityRecord) super.clone();
			baseEntity.identifier = null;
			if (baseEntity.getExtendedValues() != null) {
				Map<String, Object> temp = new HashMap<String, Object>();
				temp.putAll(baseEntity.getExtendedValues());
				baseEntity.extendedValues = temp;
			}
			return baseEntity;
		} catch (CloneNotSupportedException e) {
			throw new SystemException(e);
		}
	}
}
